package com.appcloner.data.repository

import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import com.appcloner.data.model.InstalledApp
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject

class AppRepository @Inject constructor(
    @ApplicationContext private val context: Context
) {
    
    suspend fun getInstalledApps(): List<InstalledApp> {
        val packageManager = context.packageManager
        val packages = packageManager.getInstalledPackages(PackageManager.GET_META_DATA)
        
        return packages.mapNotNull { packageInfo ->
            try {
                val appInfo = packageManager.getApplicationInfo(packageInfo.packageName, 0)
                
                InstalledApp(
                    name = packageManager.getApplicationLabel(appInfo).toString(),
                    packageName = packageInfo.packageName,
                    versionName = packageInfo.versionName ?: "Unknown",
                    versionCode = packageInfo.versionCode,
                    icon = packageManager.getApplicationIcon(appInfo),
                    isSystemApp = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
                )
            } catch (e: Exception) {
                null
            }
        }.filter { !it.isSystemApp } // 只显示用户应用
            .sortedBy { it.name.lowercase() }
    }
    
    suspend fun getAppInfo(packageName: String): InstalledApp? {
        val packageManager = context.packageManager
        return try {
            val packageInfo = packageManager.getPackageInfo(packageName, 0)
            val appInfo = packageManager.getApplicationInfo(packageName, 0)
            
            InstalledApp(
                name = packageManager.getApplicationLabel(appInfo).toString(),
                packageName = packageName,
                versionName = packageInfo.versionName ?: "Unknown",
                versionCode = packageInfo.versionCode,
                icon = packageManager.getApplicationIcon(appInfo),
                isSystemApp = (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
            )
        } catch (e: Exception) {
            null
        }
    }
}
